/*
 *	ApOS (Another Project software for s3c2410)
 *	
 *	This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License version 2 as
 *	published by the Free Software Foundation.
 *			
 *
 */
#include "../include/s3c2410/s3c2410.h"
#include "../include/s3c2410/touch_screen.h"
#include "../include/s3c2410/cpu.h"
#include "../include/s3c2410/lcd.h"
#include "../include/kernel/irq.h"
#include "../include/kernel/gui.h"
#define ITERATION 5

extern irq_ptr irq_rotunie[32];

void touchsrc_interrupt_routine(struct cpu_registers *regs);
struct touchsrc_ctrl_object touchsrc_ctrl_object;
unsigned int x_pos,y_pos;
unsigned int pos_init=0;
struct point p;

void touchscreen_ctrl_obj_init(struct touchsrc_ctrl_object *tsco)
{
	tsco->adc_con	=&rADCCON;
	tsco->adc_tsc	=&rADCTSC;
	tsco->adc_dly	=&rADCDLY;
	tsco->adc_dat0	=&rADCDAT0;
	tsco->adc_dat1	=&rADCDAT1;
}

void touchsrc_delay(unsigned short delay_val)
{
	*touchsrc_ctrl_object.adc_dly	=delay_val;
}

void touchsrc_set_prescaler(unsigned short pres_val)
{
	unsigned short adc_con	=*touchsrc_ctrl_object.adc_con;
	adc_con	&=~(0x000F<<6);
	adc_con	=(1<<14)|(pres_val<<6)|(0<<3)|(0<<2)|(0<<1)|(0);
	*touchsrc_ctrl_object.adc_con	=adc_con;
}

void touchsrc_con_init()
{
	touchsrc_delay(8000);
	*touchsrc_ctrl_object.adc_con=(1<<14)|(49<<6)|(0<<3)|(0<<2)|(0<<1)|(0);
	*touchsrc_ctrl_object.adc_tsc=(0<<8)|(1<<7)|(1<<6)|(0<<5)|(1<<4)|(0<<3)|(0<<2)|(3);
	irq_rotunie[INT_ADC]=touchsrc_interrupt_routine;
}

void wait_interrupt_mode()
{
	*touchsrc_ctrl_object.adc_tsc=(0<<8)|(1<<7)|(1<<6)|(0<<5)|(1<<4)|(0<<3)|(0<<2)|(3);
}

void auto_conversion_mode()
{
	*touchsrc_ctrl_object.adc_tsc=(1<<7)|(1<<6)|(0<<5)|(1<<4)|(1<<3)|(1<<2)|(0);
}

void conversion()
{
	*touchsrc_ctrl_object.adc_con|=0x01;
	while(*touchsrc_ctrl_object.adc_con & 0x1);       //Check if Enable_start is low
	while(!(0x8000&*touchsrc_ctrl_object.adc_con));   //Check ECFLG
}

void touchsrc_interrupt_routine(struct cpu_registers *regs)
{
	unsigned int i;

	irq_sub_mask(SUB_INT_TC,IRQ_MASK);
	irq_sub_mask(SUB_INT_ADC,IRQ_MASK);
	auto_conversion_mode();
	conversion();
	
        if(pos_init<1)
        {
        	p.x = (0x3ff&*touchsrc_ctrl_object.adc_dat0);
		p.y = (0x3ff&*touchsrc_ctrl_object.adc_dat1);
		pos_init++;
		printk("X, Y Position is (%04d , %04d)\n", p.x,p.y);
		
        }
	else
	{
		x_pos = (0x3ff&*touchsrc_ctrl_object.adc_dat0);
		y_pos = (0x3ff&*touchsrc_ctrl_object.adc_dat1);
		printk("X, Y Position is (%04d , %04d)\n", x_pos,y_pos);
		
	}
	wait_interrupt_mode();
		
	clean_sub_src_pnd(SUB_INT_TC);		
	clean_sub_src_pnd(SUB_INT_ADC);	
	clean_src_pnd(INT_ADC);	
	clean_int_pnd(INT_ADC);
	
	irq_sub_mask(SUB_INT_TC,IRQ_UNMASK);	
	irq_sub_mask(SUB_INT_ADC,IRQ_UNMASK);

}